package service.impl;

import java.util.ArrayList;
import java.util.List;

import domain.Product;
import service.ShoppingCartService;

public class ShoppingCartServiceImpl implements ShoppingCartService {

	@Override
	public List<Product> addShoppingCart(List<Product> shoppingCart, Product p) {
		if (shoppingCart == null) {
			shoppingCart = new ArrayList<Product>();
		}
		
		boolean found = false;
		boolean exceeded = false;
		String id = p.getId();
		
		for (int i = 0; i < shoppingCart.size(); i++) {
			if (shoppingCart.get(i).getId().equals(id)) {
				if (shoppingCart.get(i).getSelect() >= shoppingCart.get(i).getPnum()) {
					exceeded = true;
					break;
				}
				shoppingCart.get(i).setSelct(shoppingCart.get(i).getSelect() + 1);
				found = true;
				break;
			}
		}
		
		if (!found && !exceeded) {
			shoppingCart.add(p);
		}
		
		return shoppingCart;
	}

	@Override
	public List<Product> deleteShoppingCart(List<Product> shoppingCart, String id) {
		int index = -1;
		for (int i = 0; i < shoppingCart.size(); i++) {
			if (shoppingCart.get(i).getId().equals(id)) {
				index = i;
				break;
			}
		}
		shoppingCart.remove(index);
		return shoppingCart;
	}

}
